require 'data_mapper'
require 'dm-validations'
require 'bcrypt'

class User
    include DataMapper::Resource
    include BCrypt
    attr_reader :password_hash
    attr_accessor :password

    property :id, Serial
    property :name, String, :default => ""
    property :email, String, :unique => true, :format => :email_address, :required => true
    property :address, String, :default => ""
    property :password_hash, BCryptHash, :required => true
    property :locked, Boolean, :default => false, :writer => :public, :reader=>:public
    property :failures, Integer, :default => 0, :writer => :public, :reader=>:public
    has n, :items

    def password
        @password ||= Password.new(password_hash)
    end

    def password=(new_password)
        @password = Password.create(new_password)
        self.password_hash = @password
    end

    def self.authenticate(email, pass)
        #hash password, compare with stored hash
        user = first(:email => email)
        if user
            if user.password_hash != pass or user.locked
                user = nil
            end
        end
        return user
    end

    def to_json(*args)
        {
            'id'=> self.id,
            'name'=>self.name,
            'email'=>self.email,
            'address'=>self.address,
            'items'=>self.items,
        }.to_json(*args)
    end

end
